package com.glory.wxelectricitypda.activity;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.PackListAdapter;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.BaseResponseBean;
import com.glory.wxelectricitypda.bean.PackBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.bean.ResponseQueryBean;
import com.glory.wxelectricitypda.bean.ScrapBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class IntoDepotActivity extends BaseDialogActivity {


    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;
    @BindView(R.id.tvDepotCode)
    TextView tvDepotCode;
    @BindView(R.id.tvLotTitle)
    TextView tvLotTitle;
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.checkAll)
    CheckBox checkAll;
    @BindView(R.id.rvThingList)
    RecyclerView rvThingList;
    @BindView(R.id.flMain)
    FrameLayout flMain;
    @BindView(R.id.tvBtnThree)
    TextView tvBtnThree;
    @BindView(R.id.tvBtnTwo)
    TextView tvBtnTwo;
    @BindView(R.id.tvBtnOne)
    TextView tvBtnOne;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.llCode)
    LinearLayout llCode;

    private PackListAdapter packListAdapter;
    private FreeUI_GeneralFragmentDialog freeUI_generalFragmentDialog;
    private FreeUI_GeneralPop codePop;

    @OnClick({R.id.tvBtnOne, R.id.tvBtnTwo, R.id.tvBtnThree, R.id.llCode})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llCode:
                if (codePop == null) {
                    showToast("未请求到入库码列表", false);
                } else {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivArrow);
                        codePop.showAsDropDown(llCode, 0, 0);
                    }
                }
                break;
            case R.id.tvBtnOne:
                final List<PackBean> intoList = new ArrayList<>();
                for (PackBean entity : packListAdapter.getData()) {
                    if (entity.isSelect()) {
                        intoList.add(entity);
                    }
                }
                if (intoList.size() == 0) {
                    showToast("请勾选需要入库的批次", false);
                    return;
                }
                if (tvDepotCode.getText().toString().trim().length() == 0) {
                    showToast("未获取到入库码，请退出重进", false);
                    return;
                }
                freeUI_generalFragmentDialog = FreeApi_DialogUtils.getConfirmAndCancelDialog(getApplicationContext(), "确定要入库吗",
                        new FreeUI_CommonCallback() {
                            @Override
                            public void onSuccess() {
                                String userName = etUser.getText().toString();
                                if (userName.isEmpty()) {
                                    showToast("请输入操作人工号", false);
                                    return;
                                }
                                requestUser(userName, new CallBack() {
                                    @Override
                                    public void success() {
                                        try {
                                            JSONArray jsonArray = new JSONArray(new Gson().toJson(intoList));
                                            requestInto(jsonArray);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        freeUI_generalFragmentDialog.dismiss();
                                    }

                                    @Override
                                    public void fail() {
                                        showToast("操作人工号验证失败，请重新输入", false);
                                    }

                                    @Override
                                    public void error() {
                                        showToast("连接不到服务器，请重试", false);
                                    }
                                });
                            }
                        }, new FreeUI_CommonCallback() {
                            @Override
                            public void onSuccess() {
                                freeUI_generalFragmentDialog.dismiss();
                            }
                        });
                freeUI_generalFragmentDialog.show(getSupportFragmentManager(), "freeUI_generalFragmentDialog");
                break;
            case R.id.tvBtnTwo:
                checkAll.setChecked(false);
                packListAdapter.clearPos();
                packListAdapter.setNewData(null);
                clearAll();
                break;
            case R.id.tvBtnThree:
                checkAll.setChecked(false);
                List<PackBean> removeList = new ArrayList<>();
                for (PackBean PackBean : packListAdapter.getData()) {
                    if (PackBean.isSelect()) {
                        removeList.add(PackBean);
                    }
                }
                if (removeList.size() > 0) {
                    packListAdapter.clearPos();
                    packListAdapter.getData().removeAll(removeList);
                    packListAdapter.notifyDataSetChanged();
                    clearAll();
                } else {
                    showToast("未勾选，不能移除", false);
                }
                break;
        }
    }

    private void requestInto(JSONArray jsonArray) {
        JSONObject jsonObject2 = new JSONObject();
        try {
            jsonObject2.put("ACTIONTYPE", "SHIP");
            jsonObject2.put("ACTIONPARAM", "LOT");
            jsonObject2.put("ACTIONCODE", tvDepotCode.getText().toString().trim().split("-")[0]);
            jsonObject2.put("ACTIONCOMMENT", etRemark.getText().toString().trim());
            jsonObject2.put("LOTLIST", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestWithNormalCallBack("EUIT.EUITLOTSHIP", jsonObject2, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                new TypeToken<BaseResponseBean<?>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                if (response.body().isSuccess(getApplicationContext(), false)) {
                    List<PackBean> removeList = new ArrayList<>();
                    for (PackBean PackBean : packListAdapter.getData()) {
                        if (PackBean.isSelect()) {
                            removeList.add(PackBean);
                        }
                    }
                    packListAdapter.getData().removeAll(removeList);
                    packListAdapter.notifyDataSetChanged();
                    packListAdapter.clearPos();
                    clearAll();
                    checkAll.setChecked(false);
                    etUser.setText("");
                    showToast("入库成功", true);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                loadError(response.getException(), "入库请求");
            }
        });
    }

    private void clearAll() {
        etLotId.setText("");
        etRemark.setText("");
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_into_depot;
    }

    @Override
    protected void initView() {
        rvThingList.setLayoutManager(new LinearLayoutManager(IntoDepotActivity.this));
        rvThingList.setItemAnimator(new DefaultItemAnimator());
        rvThingList.addItemDecoration(new DividerItemDecoration(IntoDepotActivity.this, 1));
        tvBtnOne.setText("入库");
        tvBtnTwo.setText("清空");
        tvBtnThree.setText("移除");
    }

    @Override
    protected void initData() {
        requestCode();

        checkAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                packListAdapter.setAll(isChecked);
            }
        });

        etLotId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (s.length() > 0) {
                        boolean isHave = false;
                        for (PackBean entity : packListAdapter.getData()) {
                            if (entity.getLOTID().equalsIgnoreCase(s.toString())) {
                                isHave = true;
                                break;
                            }
                        }
                        if (isHave) {
                            showToast("批次号已存在列表中", false);
                        } else {
                            requestLotData(s.toString());
                        }

                    } else {
                        showToast("扫描信息有误", false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        packListAdapter = new PackListAdapter(null);
        packListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        packListAdapter.isFirstOnly(true);
        rvThingList.setAdapter(packListAdapter);
    }

    private void requestCode() {
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "BYUREFLIST");
            jsonObject1.put("ACTIONCODE", "ShipCode");
            jsonObject.put("Data",jsonObject1);
            jsonObject.put("MessageName","EUIT.EUITSCRAPCODE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<ResponseQueryBean>>(
                new TypeToken<ResponseBean<ResponseQueryBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<ResponseQueryBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<String> list = new ArrayList<>();
                    for (ScrapBean scrapBean : response.body().getBody().getSCRAPCODES()) {
                        list.add(scrapBean.getCODE() + "-" + scrapBean.getDESCRIPTION());
                    }
                    tvDepotCode.setText(list.get(0));
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), llCode.getWidth(), list, ivArrow, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvDepotCode.setText(s);
                        }
                    });
                }
            }

            @Override
            public void onError(Response<ResponseBean<ResponseQueryBean>> response) {
                super.onError(response);
                loadError(response.getException(), "入库码请求");
            }
        });
    }

    private void requestLotData(String lotID) {
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject1.put("LOTID", lotID);
            jsonObject1.put("ACTIONTYPE", "CHECKSHIPLOTINFO");
            jsonObject.put("Data",jsonObject1);
            jsonObject.put("MessageName","EUIT.EUITLOTQUERY");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<ResponseQueryBean>>(
                new TypeToken<ResponseBean<ResponseQueryBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<ResponseQueryBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    PackBean packBean = response.body().getBody().getLOT();
                    packListAdapter.addData(0, packBean);
                    rvThingList.smoothScrollToPosition(0);
                    etLotId.requestFocus();
                    etLotId.setText("");
                }
            }

            @Override
            public void onError(Response<ResponseBean<ResponseQueryBean>> response) {
                super.onError(response);
                loadError(response.getException(), "入库LOT请求");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("入库");
        return new FreeUI_AddViewEntity("header", llMain);
    }
}

